package cn.bdqn.controller;

import cn.bdqn.pojo.ItemKill;
import cn.bdqn.service.ItemKillService;
import cn.bdqn.vo.ResponseVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 秒杀商品管理
 */
@RestController
public class ItemKillController {

    private static final Logger log = LoggerFactory.getLogger(ItemKillController.class);

    @Resource
    private ItemKillService itemKillService;

    /**
     * 获取秒杀商品列表
     */
    @GetMapping("/")
    public ResponseVo list(){
        ResponseVo vo = new ResponseVo();
        try {
            List<ItemKill> itemKills = itemKillService.findAllItemKill();
            vo.setCode(200);
            vo.setMsg("获取秒杀商品列表成功");
            vo.setData(itemKills);
            log.info("获取秒杀商品列表成功：{}",itemKills);
        }catch (Exception e){
            vo.setCode(100);
            vo.setMsg("获取秒杀商品列表失败");
            vo.setData(null);
            log.error("获取秒杀商品列表-发生异常：{}",e.fillInStackTrace());
        }
        return vo;
    }

    /**
     * 根据商品ID，获取商品的详情
     * @param itemId 商品ID
     * @return
     */
    @GetMapping("/itemDetail/{itemId}")
    public ResponseVo itemDetail(@PathVariable("itemId") Integer itemId){
        ResponseVo vo = new ResponseVo();
        try {
            ItemKill itemKill = itemKillService.findByItemId(itemId);
            vo.setCode(200);
            vo.setMsg("根据商品ID获取商品详情成功");
            vo.setData(itemKill);
            log.info("根据商品ID获取商品详情：{}",itemKill);
        }catch (Exception e){
            vo.setCode(100);
            vo.setMsg("根据商品ID获取商品详情失败");
            vo.setData(null);
            log.error("根据商品ID获取商品详情-发生异常：{}",e.fillInStackTrace());
        }
        return vo;
    }

    /**
     * 秒杀核心业务处理
     * @return
     */
    @PostMapping(value = "/toKill")
    public ResponseVo toKill(Integer id,Integer userId){
        ResponseVo vo = new ResponseVo();
        try {
            int row = itemKillService.updateById4(id, userId);
            if(row > 0){
                vo.setCode(200);
                vo.setMsg("秒杀商品成功");
                vo.setData(null);
                log.info("秒杀成功");
            }
        }catch (Exception e){
            vo.setCode(100);
            vo.setMsg("秒杀商品失败");
            vo.setData(null);
            log.error("秒杀发生异常：{}"+e.fillInStackTrace());
        }
        return vo;
    }

}
